<template>
  <div class="app-container">
    <!-- 登录对话框 -->
    <div v-if="showLoginDialog" class="login-dialog">
      <div class="dialog-content">
        <h3>用户登录</h3>
        <form @submit.prevent="handleLogin">
          <div class="form-item">
            <label>用户名：</label>
            <input v-model="formData.username" type="text" required>
          </div>
          <div class="form-item">
            <label>密码：</label>
            <input v-model="formData.password" type="password" required>
          </div>
          <div class="form-item">
            <label>验证码：</label>
            <input v-model="formData.checkCode" type="text" required>
            <div v-if="isLoading" class="loading-text">加载中...</div>
            <img v-else :src="checkCodeImage" @click="getCheckCode('login')" class="checkcode-img" v-show="!checkCodeError">
            <div v-if="checkCodeError" class="error-text" @click="getCheckCode('login')">{{ checkCodeError }}</div>
          </div>
          <div class="form-actions">
            <button type="button" class="register-btn" @click="showRegisterDialog = true; getCheckCode('register')">没有账号？去注册</button>
            <button type="submit">登录</button>
            <button @click="showLoginDialog = false">取消</button>
          </div>
        </form>
      </div>
    </div>
    <!-- 注册对话框 -->
    <div v-if="showRegisterDialog" class="login-dialog">
      <div class="dialog-content">
        <h3>用户注册</h3>
        <form @submit.prevent="handleRegister">
          <div class="form-item">
            <label>公司名称：</label>
            <input v-model="registerFormData.company" type="text" required>
          </div>
          <div class="form-item">
            <label>真实姓名：</label>
            <input v-model="registerFormData.realName" type="text" required>
          </div>
          <div class="form-item">
            <label>用户名：</label>
            <input v-model="registerFormData.userName" type="text" required>
          </div>
          <div class="form-item">
            <label>密码：</label>
            <input v-model="registerFormData.registerPassword" type="password" required>
          </div>
          <div class="form-item">
            <label>手机号：</label>
            <input v-model="registerFormData.phone" type="tel" required>
          </div>
          <div class="form-item">
            <label>验证码：</label>
            <input v-model="registerFormData.checkCode" type="text" required>
            <img :src="checkCodeImage" @click="getCheckCode('register')" class="checkcode-img">
          </div>
          <div class="form-actions">
            <button type="submit">注册</button>
            <button @click="showRegisterDialog = false">取消</button>
          </div>
        </form>
      </div>
    </div>
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="logo">SCAU 会议室预定系统</div>
      <div class="header-right">
        <div class="system-notice">系统公告</div>
        <div class="avatar-dropdown">
          <!-- 绑定点击事件调用 toggleDropdown 方法 -->
          <img :src="avatarUrl" alt="Avatar" class="avatar" @click="toggleDropdown" @contextmenu.prevent="showUploadDialog" />
          <input ref="fileInput" type="file" hidden accept="image/*" @change="uploadAvatar">
          <div class="dropdown-content" v-show="isDropdownVisible">
            <button @click="login">登录</button>
            <button @click="logout">退出</button>
            <button @click="viewProfile">个人信息</button>
          </div>
        </div>
      </div>
    </header>
    <!-- 左侧导航栏 -->
    <nav class="sidebar">
      <ul>
        <li @click="activePage = 'booking'">会议室预定</li>
        <li @click="activePage = 'orders'">订单管理</li>
      </ul>
    </nav>
    <!-- 页面内容 -->
    <main class="main-content">
      <component :is="activePageComponent"></component>
    </main>
    <!-- 个人信息对话框 -->
    <div v-if="showProfileDialog" class="login-dialog">
      <div class="dialog-content">
        <h3>个人信息</h3>
        <form @submit.prevent="handleProfileUpdate">
          <div class="form-item">
            <label>用户名：</label>
            <input v-model="profileFormData.clientName" type="text" required>
          </div>
          <div class="form-item">
            <label>真实姓名：</label>
            <input v-model="profileFormData.realname" type="text" required>
          </div>
          <div class="form-item">
            <label>密码：</label>
            <input v-model="profileFormData.password" type="password" required>
          </div>
          <div class="form-item">
            <label>手机号：</label>
            <input v-model="profileFormData.phone" type="tel" required>
          </div>
          <div class="form-item">
            <label>公司名称：</label>
            <input v-model="profileFormData.company" type="text" required>
          </div>
          <div class="form-actions">
            <button type="submit">保存</button>
            <button @click="showProfileDialog = false">取消</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
import BookingPage from './BookingPage.vue';
import OrdersPage from './OrdersPage.vue';
import axios from 'axios';
import qs from 'querystring';

export default {
  components: {
    BookingPage,
    OrdersPage
  },
  data() {
    return {
      activePage: 'booking',
      isDropdownVisible: false,
      avatarUrl: '/img/icons/default-avatar.svg',
      showLoginDialog: false,
      showRegisterDialog: false,
      registerFormData: {
        company: '',
        realName: '',
        userName: '',
        registerPassword: '',
        phone: '',
        checkCode: '',
        checkCodeKey: ''
      },
      formData: {
        username: '',
        password: '',
        checkCode: '',
        checkCodeKey: '',
      },
      profileFormData: {
        clientName: '',
        realname: '',
        password: '',
        phone: '',
        company: ''
      },
      uploadLoading: false,
      uploadError: null,
      showProfileDialog: false,
      checkCodeImage: '',
      isLoading: false,
      checkCodeError: null
    };
  },
  computed: {
    activePageComponent() {
      switch (this.activePage) {
        case 'booking':
          return 'BookingPage';
        case 'orders':
          return 'OrdersPage';
        default:
          return 'BookingPage';
      }
    }
  },
  methods: {
    async fetchAvatar() {
      try {
        const response = await axios.get('/api/customer/account/avator', {
          responseType: 'blob'
        });
        const blob = new Blob([response.data], {
          type: response.headers['content-type']
        });
        this.avatarUrl = URL.createObjectURL(blob);
      } catch (error) {
        console.error('头像获取失败:', error);
        this.avatarUrl = '/img/icons/default-avatar.svg';
      }
    },
    async getCheckCode(type='login') {
      this.isLoading = true;
      this.checkCodeError = null;
      try {
        const response = await axios.get('/api/customer/account/checkCode');
        const data = response.data;
        if(data.code === 200) {
          this.checkCodeImage = data.data.checkCode;
          if(type === 'login') {
          this.formData.checkCodeKey = data.data.checkCodeKey;
        } else {
          this.registerFormData.checkCodeKey = data.data.checkCodeKey;
        }
        }
      } catch (error) {
        console.error('验证码获取失败:', error);
        this.checkCodeError = '验证码加载失败，点击重试';
        setTimeout(() => this.getCheckCode(), 300000);
      } finally {
        this.isLoading = false;
      }
    },
    async handleLogin() {
      this.isLoading = true;
      try {
        const response = await axios.post('/api/customer/account/login', qs.stringify(this.formData), {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        });
        const data = response.data;
        
        if(data.code === 200) {
          this.showLoginDialog = false;
          alert('登录成功');
          await this.fetchAvatar();
        } else {
          this.checkCodeError = data.data || '登录失败';
          this.getCheckCode();
        }
      } catch (error) {
        console.error('登录请求失败:', error);
        this.checkCodeError = error.response?.data?.msg || '网络异常，请重试';
        this.getCheckCode();
      } finally {
        this.isLoading = false;
      }
    },
    async handleRegister() {
      try {
        const response = await axios.post('/api/customer/account/register', qs.stringify(this.registerFormData), {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        });
        const data = response.data;
        
        if(data.code === 200) {
          this.showRegisterDialog = false;
          alert('注册成功，请登录');
        } else {
          alert(data.msg || '注册失败');
        }
      } catch (error) {
        console.error('注册请求失败:', error);
        alert(error.response?.data?.msg || '网络异常，请重试');
      }
    },
    login() {
      this.showLoginDialog = true;
      this.getCheckCode();
    },
    async logout() {
      try {
        const response = await axios.get('/api/customer/account/loginout');
        if(response.data.code === 200) {
          this.avatarUrl = '/img/icons/default-avatar.svg';
          this.isDropdownVisible = false;
          this.profileFormData = {
            clientName: '',
            realname: '',
            password: '',
            phone: '',
            company: ''
          };
          alert('退出成功');
        } else {
          alert(response.data.msg || '退出失败');
        }
      } catch (error) {
        console.error('退出请求失败:', error);
        alert(error.response?.data?.msg || '网络异常');
      }
    },
    async viewProfile() {
      try {
        const response = await axios.get('/api/customer/account');
        if(response.data.code === 200) {
          this.profileFormData = {
  clientName: response.data.data?.clientName || '',
  realname: response.data.data?.realname || '',
  password: '',
  phone: response.data.data?.phone || '',
  company: response.data.data?.company || ''
};
          
          this.showProfileDialog = true;
        }
      } catch (error) {
        console.error('获取个人信息失败:', error);
        alert('获取信息失败');
      }
    },
    toggleDropdown() {
      this.isDropdownVisible = !this.isDropdownVisible;
    },

    showUploadDialog() {
      this.$refs.fileInput.click();
    },

    async uploadAvatar(event) {
      const file = event.target.files[0];
      if (!file) return;

      this.uploadLoading = true;
      this.uploadError = null;

      try {
        const formData = new FormData();
        formData.append('file', file);

        const response = await axios.post('/api/customer/account/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });

        if (response.data.code === 200) {
          this.avatarUrl = URL.createObjectURL(file);
          alert('头像更新成功');
        } else {
          this.uploadError = response.data.msg || '上传失败';
        }
      } catch (error) {
        console.error('上传请求失败:', error);
        this.uploadError = error.response?.data?.msg || '网络异常';
      } finally {
        this.uploadLoading = false;
        event.target.value = '';
      }
    },
    async handleProfileUpdate() {
      try {
        const response = await axios.post(
          '/api/customer/account/update',
          qs.stringify(this.profileFormData),
          {
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
            }
          }
        );
        if(response.data.code === 200) {
          alert('修改成功');
          this.showProfileDialog = false;
        }
      } catch (error) {
        console.error('更新失败:', error);
        alert('更新失败');
      }
    }
  },
  async mounted() {
    try {
      const response = await axios.get('/api/customer/account/autoLogin');
      const data = response.data;
      if(data.code === 200) {
        this.profileFormData = data.data;
        alert('自动登录成功');
          await this.fetchAvatar();
      } else {
        throw new Error('自动登录失败');
      }
    } catch (error) {
      console.error('自动登录请求异常:', error);
    }
  }
};
</script>

<style scoped>
.login-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.dialog-content {
  background: white;
  padding: 20px;
  border-radius: 8px;
  min-width: 350px;
}

.form-item {
  margin: 15px 0;
}

.form-item label {
  display: block;
  margin-bottom: 5px;
}

.form-item input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.checkcode-img {
  margin-top: 10px;
  height: 40px;
  cursor: pointer;
  border: 1px solid #ddd;
  padding: 2px;
}

.form-actions {
  margin-top: 20px;
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

.form-actions button {
  padding: 8px 15px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.form-actions button[type='submit'] {
  background: #1976d2;
  color: white;
}

.app-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 60px;
  background-color: #1976d2;
  color: white;
}

.logo {
  font-size: 20px;
  font-weight: bold;
  color: white;
}

.header-right {
  display: flex;
  align-items: center;
}

.system-notice {
  margin-right: 20px;
  color: white;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  cursor: pointer;
}

.avatar-dropdown {
  position: relative;
}

.dropdown-content {
  position: absolute;
  right: 0;
  top: 100%;
  background-color: white;
  border: 1px solid #ccc;
  min-width: 120px;
  z-index: 1;
}

.dropdown-content button {
  display: block;
  width: 100%;
  padding: 10px;
  border: none;
  background-color: transparent;
  cursor: pointer;
}

.dropdown-content button:hover {
  background-color: #1976d2;
  color: white;
}

.sidebar {
  width: auto;
  background-color: #f8f9fa;
  padding: 10px 20px;
}

.sidebar ul {
  display: flex;
  gap: 20px;
  margin: 0;
  padding: 0;
}

.sidebar li {
  margin: 0 10px 0 0;
  padding: 10px 15px;
}

.sidebar li:hover {
  background-color: #bbdefb;
}

.dropdown-content button {
  display: block;
  width: 100%;
  padding: 10px;
  border: none;
  background-color: #2196f3;
  color: white;
  cursor: pointer;
  transition: background-color 0.2s;
}

.dropdown-content button:hover {
  background-color: #1976d2;
}

.main-content {
  flex: 1;
  padding: 20px;
}

.register-btn {
  font-size: 12px;
  padding: 4px 8px;
  background: transparent;
  color: #1976d2;
  border: none;
  cursor: pointer;
  margin-right: auto;
}

.register-btn:hover {
  text-decoration: underline;
}
</style>